package com.jiezuo.flowable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.flowable.entity.MessageRouter;
import com.jiezuo.flowable.entity.MessageRouterDetails;
import com.jiezuo.flowable.mapper.MessageRouterMapper;
import com.jiezuo.flowable.service.MessageRouterDetailsService;
import com.jiezuo.flowable.service.MessageRouterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 消息路由配置
 * @author 庞留杰
 * @date 2024/08/22 08:59
 * @version V1.0
 **/
@Transactional
@Slf4j
@Service
public class MessageRouterServiceImpl extends ServiceImpl<MessageRouterMapper, MessageRouter> implements MessageRouterService {

    @Autowired
    MessageRouterDetailsService messageRouterDetailsService;

    @Override
    public IPage<MessageRouter> findPage(Page initMpPage, MessageRouter messageRouter) {
        QueryWrapper<MessageRouter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        Page<MessageRouter> page = this.page(initMpPage, queryWrapper);
        List<MessageRouter> list = page.getRecords();
        List<String> ids = list.stream().map(it -> it.getId()).collect(Collectors.toList());
        if (ids.size() > 0) {
            QueryWrapper<MessageRouterDetails> detailsQueryWrapper = new QueryWrapper<>();
            detailsQueryWrapper.eq("is_delete", "0");
            detailsQueryWrapper.in("router_id", ids);
            List<MessageRouterDetails> detailList = messageRouterDetailsService.list(detailsQueryWrapper);
            for (MessageRouter mr : list) {
                List<MessageRouterDetails> details = detailList.stream().filter(d -> mr.getId().equals(d.getRouter_id())).collect(Collectors.toList());
                mr.setDetails(details);
            }
        }
        return page;
    }

    @Override
    public List<MessageRouter> findList(MessageRouter messageRouter) {
        QueryWrapper<MessageRouter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        List<MessageRouter> list = this.list(queryWrapper);
        List<String> ids = list.stream().map(it -> it.getId()).collect(Collectors.toList());
        if (ids.size() > 0) {
            QueryWrapper<MessageRouterDetails> detailsQueryWrapper = new QueryWrapper<>();
            detailsQueryWrapper.eq("is_delete", "0");
            detailsQueryWrapper.in("router_id", ids);
            List<MessageRouterDetails> detailList = messageRouterDetailsService.list(detailsQueryWrapper);
            for (MessageRouter mr : list) {
                List<MessageRouterDetails> details = detailList.stream().filter(d -> mr.getId().equals(d.getRouter_id())).collect(Collectors.toList());
                mr.setDetails(details);
            }
        }
        return list;
    }

    @Override
    public MessageRouter findById(String id) {
        return this.getById(id);
    }

    @Override
    public boolean add(MessageRouter messageRouter) {
        boolean save = this.save(messageRouter);
        // 处理详情
        List<MessageRouterDetails> details = messageRouter.getDetails();
        if (details!=null && details.size()>0) {
            List<String> activity_ids = details.stream().map(it -> it.getActivity_id()).collect(Collectors.toList());
            if (activity_ids.size() > 0) {
                QueryWrapper<MessageRouterDetails> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("activity_id", activity_ids);
                queryWrapper.eq("is_delete", "0");
                List<MessageRouterDetails> list = messageRouterDetailsService.list(queryWrapper);
                if (list.size() > 0) {
                    String activity_id = list.get(0).getActivity_id();
                    throw new BusinessRuntimeException("流程活动ID[%s]已与其他路由设置绑定，请勿重复绑定！", activity_id);
                }
            } else {
                for (MessageRouterDetails detail : details) {
                    detail.setRouter_id(messageRouter.getId());
                }
                messageRouterDetailsService.saveBatch(details);
            }
        }
        return save;
    }

    @Override
    public boolean update(MessageRouter messageRouter) {
        boolean update = this.updateById(messageRouter);
        // 处理详情
        String id = messageRouter.getId();
        List<MessageRouterDetails> details = messageRouter.getDetails();
        for (MessageRouterDetails detail : details) {
            QueryWrapper<MessageRouterDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("activity_id", detail.getActivity_id());
            queryWrapper.ne("router_id", id);
            queryWrapper.eq("type", detail.getType());
            queryWrapper.eq("is_delete", "0");
            List<MessageRouterDetails> list = messageRouterDetailsService.list(queryWrapper);
            if (list.size() > 0) {
                String activity_id = list.get(0).getActivity_id();
                throw new BusinessRuntimeException("流程活动ID[%s]已与其他路由设置绑定，请勿重复绑定！", activity_id);
            }
        }
        // 删除旧的
        UpdateWrapper<MessageRouterDetails> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("router_id", id);
        updateWrapper.eq("is_delete", "0");
        updateWrapper.set("is_delete", "1");
        messageRouterDetailsService.update(updateWrapper);
        // 添加新的
        for (MessageRouterDetails detail : details) {
            detail.setId(null);//清理原有的ID
            detail.setRouter_id(messageRouter.getId());
        }
        messageRouterDetailsService.saveBatch(details);
        return update;
    }

    @Override
    public boolean delete(String id) {
        MessageRouter messageRouter = new MessageRouter();
        messageRouter.setId(id);
        messageRouter.setIs_delete("1");
        boolean update = this.updateById(messageRouter);
        // 删除详情
        UpdateWrapper<MessageRouterDetails> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("router_id", id);
        updateWrapper.eq("is_delete", "0");
        updateWrapper.set("is_delete", "1");
        messageRouterDetailsService.update(updateWrapper);
        return update;
    }

}
